package com.qz.mos.entity;

import com.qz.mos.Mos2Application;
import com.qz.mos.jpa.RestDataMD5Jpa;
import org.springframework.beans.BeansException;

import javax.persistence.AttributeConverter;

public class RestDataMD5Converter implements AttributeConverter<RestDataMD5,String> {
    /**
     * Converts the value stored in the entity attribute into the
     * data representation to be stored in the database.
     *
     * @param attribute the entity attribute value to be converted
     * @return the converted data to be stored in the database
     * column
     */
    @Override
    public String convertToDatabaseColumn(RestDataMD5 attribute) {
        if(attribute==null)return null;
        String id = attribute.getId();
        if(id==null){
            id=Md5Id.encrypt3ToMD5(attribute);
        }
        RestDataMD5 restDataMD5 = getRestDataMD5( id );
        if(restDataMD5==null){
            try {
                RestDataMD5Jpa bean = Mos2Application.applicationContext.getBean( RestDataMD5Jpa.class );
                bean.save( attribute );
            } catch (BeansException e) {
                e.printStackTrace();
            }
        }
        return id;
    }

    /**
     * Converts the data stored in the database column into the
     * value to be stored in the entity attribute.
     * Note that it is the responsibility of the converter writer to
     * specify the correct <code>dbData</code> type for the corresponding
     * column for use by the JDBC driver: i.e., persistence providers are
     * not expected to do such type conversion.
     *
     * @param dbData the data from the database column to be
     *               converted
     * @return the converted value to be stored in the entity
     * attribute
     */
    @Override
    public RestDataMD5 convertToEntityAttribute(String dbData) {
        if(dbData==null)return null;
        //判断数据库中是否存在
        return getRestDataMD5( dbData );
    }

    private static RestDataMD5 getRestDataMD5(String dbData) {
        RestDataMD5Jpa bean = Mos2Application.applicationContext.getBean( RestDataMD5Jpa.class );
        return bean.findById( dbData ).orElse( null );
    }
}
